/*
 Hidamari - A simple batch m4v/mp4 tagger for iTunes
 Copyright (C) 2008 Jason Stone
 
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>
 */

#import "MyDocument.h"
#import <dispatch/dispatch.h>

@implementation MyDocument

@synthesize showName;

- (id)init
{
    self = [super init];
    if (self) {
    
        // Add your subclass-specific initialization here.
        // If an error occurs here, send a [self release] message and return nil.
		epList = [[NSMutableArray alloc] init];
		fileList = [[NSMutableArray alloc] init];
		
		NSSortDescriptor *es = [[NSSortDescriptor alloc] initWithKey:@"num" ascending:YES];
		NSSortDescriptor *fs = [[NSSortDescriptor alloc] initWithKey:@"filenum" ascending:YES];
		
		epSort = [NSArray arrayWithObject:es];
		fSort = [NSArray arrayWithObject:fs];
		
    }
    return self;
}

-(IBAction) populateFilenames: (id) sender{
	NSArray *filetypes = [NSArray arrayWithObjects:@"m4v",@"mp4",nil];
	NSOpenPanel *opPanel = [NSOpenPanel openPanel];
	[opPanel setAllowsMultipleSelection:YES];
	
	int result = [opPanel runModalForDirectory:NSHomeDirectory() file:nil types:filetypes];
	if(result == NSOKButton){
		NSArray *res = [opPanel filenames];
		int i = 1;
		for(NSString *file in res){
			FileWrapper *temp = [[FileWrapper alloc] initWithNum:i name:[[NSString alloc] initWithString:file] path:[[NSString alloc] initWithString:file]];
			[[self mutableArrayValueForKey:@"fileList"] addObject: temp];
			i++;
		}
		
		for(FileWrapper *f in fileList){
			[f setFileName:[f.fileName lastPathComponent]];
		}
	}
	
}

-(IBAction) logEpList: (id) sender{
	for(Episode *e in epList){
		NSLog(@"%@",[e stringValue]);
	}
	
	[epList sortUsingDescriptors:epSort];
}

-(IBAction) logFileList: (id) sender{
	for(FileWrapper *f in fileList){
		NSLog(@"%@",[f stringValue]);
	}
}

-(IBAction) doConvert: (id) sender{
	if (![goButton isEnabled]) {
		return;
	}
	[goButton setIgnoresMultiClick:true];
	[goButton setEnabled:false];
	
	[progressBar setMaxValue:epCount];
	[epList sortUsingDescriptors:epSort];
	[fileList sortUsingDescriptors:fSort];
	
	if([epList count] != [fileList count]){
		NSRunAlertPanel(@"Error", @"Episode count must match file count", @"OK", @"", @"");
		[goButton setEnabled:true];
		return;
	}
	
	//Grand Central Awesome indeed...

	dispatch_apply(epCount, dispatch_get_global_queue(0, 0), ^(size_t num){
		Episode *currEp = [epList objectAtIndex:num];
		FileWrapper *currFile = [fileList objectAtIndex:num];
		NSLog(@"%@",[currEp stringValue]);
		NSLog(@"%@",[currFile stringValue]);
		NSMutableArray *args = [NSMutableArray arrayWithObject:currFile.path];
		
		[args addObject:@"-STV Show"];
		[args addObject:[NSString stringWithFormat:@"-H%@",showName]];
		[args addObject:[NSString stringWithFormat:@"-U%d",season]];
		[args addObject:[NSString stringWithFormat:@"-N%d",currEp.num]];
		
		NSString *fullTitle;
		if(hasJ){
			fullTitle = [NSString stringWithFormat:@"%@ - %@",currEp.title,currEp.jTitle];
		}
		else{
			fullTitle = currEp.title;
		}
		[args addObject:@"--title"];
		[args addObject:fullTitle];
		
		if(hasDesc){
			//Couldn't just use -p, AtomicParsley segfaults...
			[args addObject:@"--description"];
			[args addObject:currEp.description];
		}
		
		NSTask *task = [[NSTask alloc] init];
		[task setLaunchPath:[[NSBundle mainBundle] pathForResource:@"AtomicParsley" ofType:@""]];
		NSLog(@"%@",[task launchPath]);
		[task setArguments:args];
		[task launch];
		[task waitUntilExit];
		dispatch_async(dispatch_get_main_queue(), ^{
			[progressBar incrementBy:1.0];
		});
		
	});
	[goButton setEnabled:true];
	
	
	
	
	
	/*for(int num = 0; num < epCount; num++){
		currEp = [epList objectAtIndex:num];
		currFile = [fileList objectAtIndex:num];
		NSLog(@"%@",[currEp stringValue]);
		NSLog(@"%@",[currFile stringValue]);
		args = [NSMutableArray arrayWithObject:currFile.path];
		
		[args addObject:@"-STV Show"];
		[args addObject:[NSString stringWithFormat:@"-H%@",showName]];
		[args addObject:[NSString stringWithFormat:@"-U%d",season]];
		[args addObject:[NSString stringWithFormat:@"-N%d",currEp.num]];
		
		if(hasJ){
			fullTitle = [NSString stringWithFormat:@"%@ - %@",currEp.title,currEp.jTitle];
		}
		else{
			fullTitle = currEp.title;
		}
		[args addObject:@"--title"];
		[args addObject:fullTitle];
		
		if(hasDesc){
			//Couldn't just use -p, AtomicParsley segfaults...
			[args addObject:@"--description"];
			[args addObject:currEp.description];
		}
		
		task = [[NSTask alloc] init];
		[task setLaunchPath:[[NSBundle mainBundle] pathForResource:@"AtomicParsley" ofType:@""]];
		NSLog(@"%@",[task launchPath]);
		[task setArguments:args];
		[task launch];
		[task waitUntilExit];
		[progressBar incrementBy:1.0];
	}*/
	
	
	
}


- (NSString *)windowNibName
{
    // Override returning the nib file name of the document
    // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead.
    return @"MyDocument";
}

- (void)windowControllerDidLoadNib:(NSWindowController *) aController
{
    [super windowControllerDidLoadNib:aController];
    // Add any code here that needs to be executed once the windowController has loaded the document's window.
	
	[epCont setSortDescriptors:epSort];
	[fCont setSortDescriptors:fSort];
}

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
    // Insert code here to write your document to data of the specified type. If the given outError != NULL, ensure that you set *outError when returning nil.

    // You can also choose to override -fileWrapperOfType:error:, -writeToURL:ofType:error:, or -writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.

    // For applications targeted for Panther or earlier systems, you should use the deprecated API -dataRepresentationOfType:. In this case you can also choose to override -fileWrapperRepresentationOfType: or -writeToFile:ofType: instead.

    if ( outError != NULL ) {
		*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
	}
	return nil;
}

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
    // Insert code here to read your document from the given data of the specified type.  If the given outError != NULL, ensure that you set *outError when returning NO.
	NSString *file = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	NSArray *lines = [file componentsSeparatedByString:@"\n"];
	NSArray *header = [lines objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0,6)]];
	NSArray *eps = [lines objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(6,[lines count]-6)]];
	if([[header objectAtIndex:0] compare: (NSString *)@"[EPFILE]"] == 0){
		NSLog(@"Good File. Loading...");
	}
	
	showName = [[NSString alloc] initWithString:[header objectAtIndex:1]];
	NSLog(@"Title of show is %@",showName);
	
	season = [[header objectAtIndex:2] intValue];
	NSLog(@"Season of show is %d",season);
	
	epCount = [[header objectAtIndex:3] intValue];
	NSLog(@"Number of episodes is %d",epCount);
	[progressBar setMaxValue:epCount];
	
	hasJ = ([[header objectAtIndex:4] compare: (NSString *)@"Y"] == 0);
	NSLog(@"Has Japanese/Alt Title? %d",hasJ);
	
	hasDesc = ([[header objectAtIndex:5] compare: (NSString *)@"Y"] == 0);
	NSLog(@"Has Descriptions? %d", hasDesc);
	
	NSLog(@"Header read. Reading episodes...");
	int multiplier = 2;
	if(hasJ) multiplier++;
	if(hasDesc) multiplier++;
	NSLog(@"%d lines per episode.",multiplier);
	
	for(int i = 0; i < epCount; i++){
		Episode *tempEp = [[Episode alloc] init];
		
		tempEp.num = [[eps objectAtIndex:multiplier * i] intValue];
		tempEp.title = [eps objectAtIndex:multiplier * i + 1];
		if(hasJ) tempEp.jTitle = [eps objectAtIndex:multiplier * i + 2];
		if(hasDesc && hasJ) tempEp.description = [eps objectAtIndex:multiplier * i + 3];
		else if (!hasJ && hasDesc) tempEp.description = [eps objectAtIndex:multiplier * i + 2];
		
		[[self mutableArrayValueForKey:@"epList"] addObject:tempEp];
	}
	
    // You can also choose to override -readFromFileWrapper:ofType:error: or -readFromURL:ofType:error: instead. 
    
    // For applications targeted for Panther or earlier systems, you should use the deprecated API -loadDataRepresentation:ofType. In this case you can also choose to override -readFromFile:ofType: or -loadFileWrapperRepresentation:ofType: instead.
    
    if ( outError != NULL ) {
		*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
	}
    return YES;
}

@end
